package smecta.client.print.service;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import smecta.client.print.domain.ScpSysSettings;
import smecta.client.print.mapper.ScpSysSettingsMapper;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ScpSysSettingsService extends BaseService<ScpSysSettings> {

    @Autowired
    private ScpSysSettingsMapper scpSysSettingsMapper;

    public Map<String,List<String>> getKeyValueListMap(List<String> choiceBoxList){
        Map<String,List<String>> resultMap = new HashMap<>();
        if (CollectionUtils.isEmpty(choiceBoxList)){
            return resultMap;
        }
        List<ScpSysSettings> list = getModelListByKeyList(choiceBoxList);
        if (CollectionUtils.isNotEmpty(list)){
            for (ScpSysSettings scpSysSettings : list) {
                scpSysSettings.makeSettingValueList();
                resultMap.put(scpSysSettings.getSettingKey(),scpSysSettings.getSettingValueList());
            }
        }

        return resultMap;
    }

    public List<ScpSysSettings> getModelListByKeyList(List<String> keyList){
        if (CollectionUtils.isEmpty(keyList)){
            return new ArrayList<>();
        }
        Example example = new Example(ScpSysSettings.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("settingKey",keyList);
        return selectByExample(example);
    }

    public ScpSysSettings findByKey(String key){
        ScpSysSettings model = new ScpSysSettings();
        model.setSettingKey(key);
        return selectOne(model);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateKeyOrInit(String key, String value) {
        if (StringUtils.isBlank(key) || StringUtils.isBlank(value)){
            return;
        }
        ScpSysSettings model = findByKey(key);
        if (model == null){
            ScpSysSettings insertModel = new ScpSysSettings();
            insertModel.setSettingKey(key);
            insertModel.setSettingValue(value);
            insertModel.setSettingValueType("STRING");
            insertSelective(insertModel);
            return;
        }

        ScpSysSettings updateModel = new ScpSysSettings();
        updateModel.setId(model.getId());
        updateModel.setSettingValue(value);
        updateByPrimaryKeySelective(updateModel);
    }
}
